<template>
  <div class="form-page">
    <div class="block-wrap form-container">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="8em"
        v-loading="formLoading"
      >
        <el-form-item label="所属机构" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择所属机构">
            <el-optioncnpm
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"  
            ></el-optioncnpm>
          </el-select>
        </el-form-item>
        <el-form-item label="选择角色" prop="role">
          <el-select
            v-model="form.role"
            multiple
            :multiple-limit="multipleLimit"
            placeholder="请选择角色"
          >
            <div class="roleRuls">最多可选三个角色</div>
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员账户" prop="username">
          <el-input
            v-model.trim="form.username"
            placeholder="长度为5~20个字符，只能包含汉字、字母、数字"
            clearable
          />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input
            v-model.trim="form.password"
            placeholder="长度为6~25个字符，只能包含字母、数字、符号"
            :type="passwordType"
          />
          <span
            class="show-pwd"
            @click="
              passwordType = passwordType === 'password' ? '' : 'password'
            "
          >
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
        <el-form-item label="确认密码" prop="newpassword1">
          <el-input
            v-model.trim="form.newpassword1"
            placeholder="再次输入登录密码"
            :type="passwordReType"
          />
          <span
            class="show-pwd"
            @click="
              passwordReType = passwordReType === 'password' ? '' : 'password'
            "
          >
            <svg-icon
              :icon-class="passwordReType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model.trim="form.realName"
            placeholder="用户的真实姓名，2~20个字符"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="form.phone" placeholder="请输入11位手机号" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :autosize="{ minRows: 2 }"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm"
            >提交</el-button
          >
          <el-button type="default" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <div class="subImg">
        <img src="@/assets/manageSub.png" alt="" />
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogTableVisible"
      width="560px"
      :show-close="false"
      top="25vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-result icon="success" title="创建用户成功">
        <template slot="extra">
          <el-button type="primary" size="medium" @click="continueAdd"
            >继续创建</el-button
          >
          <el-button size="medium" @click="gotoManaList">返回列表</el-button>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDeptFindAll,
  getRoleList,
  addUser,
  getUserById,
  updateUser
} from "@/api/sys";
export default {
  name: "AddManage",
  data() {
    const validateUsername = (rule, value, callback) => {
      let reg = new RegExp("^[A-Za-z0-9\u4e00-\u9fa5]+$");
      if (!reg.test(value)) {
        callback(new Error("只能包含汉字、字母或数字！"));
      } else {
        callback();
      }
    };
    const validatenewpassword1 = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error("两次输入的密码不一致，请重新输入。"));
      } else {
        callback();
      }
    };
    return {
      passwordType: "password",
      passwordReType: "password",
      loading: false,
      form: {
        deptId: "",
        username: "",
        password: "",
        newpassword1: "",
        realName: "",
        phone: "",
        role: [],
        remark: ""
      },
      multipleLimit: 3,
      rules: {
        deptId: [
          { required: true, message: "请选择所属机构", trigger: "change" }
        ],
        username: [
          { required: true, message: "请输入账号名", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur"
          },
          { trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          { min: 6, max: 25, message: "长度为6~25个字符", trigger: "blur" }
        ],
        newpassword1: [
          { required: true, message: "请输入确认新密码", trigger: "blur" },
          { trigger: "blur", validator: validatenewpassword1 }
        ],
        realName: [
          {
            required: true,
            message: "请输入2~20个字符的姓名",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "请输入2~20个字符的姓名",
            trigger: "blur"
          },
          {
            pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/,
            message: "请勿输入特殊字符",
            trigger: "blur"
          }
        ],
        phone: [
          { required: true, message: "请输入11位手机号", trigger: "blur" },
          {
            pattern: /^1\d{10}$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        role: [
          { required: true, message: "请选择要分配的角色", trigger: "blur" }
        ]
      },
      deptList: [],
      roleList: [],
      dialogTableVisible: false,
      formLoading: false
    };
  },
  watch: {
    $route: {
      handler() {
        let { userId } = this.$route.query;
        if (userId) {
          this.$route.meta.title = "编辑管理员";
          this.getUserById(userId);
        } else {
          this.$route.meta.title = "新增管理员";
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    getDeptFindAll().then(res => {
      this.deptList = res.data;
    });
    getRoleList().then(res => {
      this.roleList = res.data;
    });
  },
  methods: {
    //根据id获取管理员数据
    getUserById(id) {
      this.formLoading = true;
      getUserById(id)
        .then(res => {
          let {
            deptId,
            username,
            password,
            newpassword1,
            realName,
            phone,
            roleList,
            remark
          } = res.data;
          let roleIdArr = [];
          roleList.forEach(element => {
            roleIdArr.push(element.roleId);
          });
          this.form = {
            deptId: deptId.toString(),
            username: username,
            password: password,
            newpassword1: newpassword1,
            realName: realName,
            phone: phone,
            remark: remark,
            role: roleIdArr
          };
          this.formLoading = false;
        })
        .catch(() => {
          this.formLoading = false;
        })
        .finally(() => {
          this.formLoading = false;
        });
    },
    submitForm() {
      this.loading = true;
      this.$refs.form.validate(valid => {
        if (valid) {
          let { userId } = this.$route.query;
          if (!userId) {
            this.addUser();
          } else {
            this.editUser();
          }
        } else {
          console.log("error submit!!");
          this.loading = false;
          return false;
        }
      });
    },
    addUser() {
      addUser(this.form)
        .then(res => {
          if (res.code === 200) {
            this.dialogTableVisible = true;
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    editUser() {
      this.form.userId = this.$route.query.userId;
      updateUser(this.form)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("更新成功");
            this.loading = false;
            this.$router.push({ name: "Manage" });
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    cancel() {
      this.$router.go(-1);
    },
    continueAdd() {
      this.loading = false;
      this.dialogTableVisible = false;
      this.form = {
        deptId: "",
        username: "",
        password: "",
        newpassword1: "",
        realName: "",
        phone: "",
        role: [],
        remark: ""
      };
    },
    gotoManaList() {
      this.loading = false;
      this.dialogTableVisible = false;
      this.$router.push({ name: "Manage" });
    }
  }
};
</script>

<style lang="scss">
@import "~@/styles/page/form-page.scss";
</style>
<style lang="scss" scoped>
.form-page {
  .form-container {
    margin-bottom: 0;
    padding: 0;
    overflow: hidden;
    .el-form {
      float: left;
      width: 760px;
      margin-left: 182px;
      margin-top: 69px;
      .el-button--primary {
        background-color: #1890ff;
        border-color: #1890ff;
      }
    }
    .subImg {
      float: left;
      margin-left: 196px;
      margin-top: 168px;
    }
  }
  ::v-deep.el-dialog {
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      padding: 0;
    }
  }
  .el-button.el-button--primary.el-button--medium {
    background-color: #1890ff;
    border-color: #1890ff;
  }
}
.block-wrap {
  padding: 25px;
  background: #fff;
  border-radius: 2px;
}
.roleRuls {
  padding: 9px 20px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #fd1515;
  line-height: 17px;
}
</style>
